<template>
  <div id="message">
    <div class="search">
      <van-search
        v-model="name"
        shape="round"
        placeholder="搜索"
        @update:model-value="search"
      />
    </div>
    <div class="list">
      <van-empty
        v-if="flag"
        image="https://fastly.jsdelivr.net/npm/@vant/assets/custom-empty-image.png"
        image-size="80"
        description="暂无内容"
        style="margin-top: 20%"
      />
      <div class="ls" v-for="item in newlist" :key="item._id">
        <van-swipe-cell
          right-width="150"
          :style="
            item.istop === false
              ? 'background-color: #fff'
              : 'background-color: #dfeedf'
          "
        >
          <img
            :src="
              item.imgsrc
                ? item.imgsrc
                : item.sex == 1
                ? '/icon/男生默认头像.png'
                : '/icon/女生默认头像.png'
            "
            alt=""
            class="tou"
          />
          <span class="ls_name">{{ item.uname }}</span>
          <span class="ls_test"
            ><span v-if="item.isread" style="color: red; margin-right: 0.5rem"
              >[new]</span
            >{{ new_message(item)[0] }}</span
          >
          <span class="ls_time">{{ new_message(item)[1] }}</span>
          <span v-if="item.isread" class="red"></span>
          <img src="/icon/信息2.png" alt="" class="go" @click="go_chat(item)" />
          <template #right>
            <van-button
              square
              type="warning"
              :text="item.istop === false ? '置顶' : '取消置顶'"
              class="button"
              @click="istop(item._id)"
              style="background-color: #eaa555; border-color: #eaa555"
            />
            <van-button
              square
              type="danger"
              text="删除"
              class="button"
              @click="del(item._id)"
            />
          </template>
        </van-swipe-cell>
      </div>
    </div>
  </div>
</template>
  
<script setup>
import { ref, reactive, watch, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useCounterStore } from "../../stores/counter";
import axios from "axios";
import { io } from "socket.io-client";
const useStore = useCounterStore();
const router = useRouter();

// 搜索内容
const name = ref("");
const search = () => {
  console.log(name.value);
};

const flag = ref(false);
// 搜索后的列表
const newlist = computed(() => {
  let newlist = list.value.filter((item) => {
    return item.uname.includes(name.value);
  });
  if (newlist.length === 0) {
    flag.value = true;
  } else {
    flag.value = false;
  }
  return newlist.sort((a, b) => {
    return b.istop - a.istop;
  });
});

const user_id = useStore.info._id;

// 用户列表
const list = computed(() =>
  useStore.list.filter((item) => {
    return item._id !== user_id;
  })
);

const socket = io("http://localhost:4000", {
  connected: true, // 是否自动重连
  reconnectionAttempts: 3, // 重连尝试次数
  reconnectionDelay: 1000, // 重连延迟时间（毫秒）
  reconnectionDelayMax: 5000, // 最大重连延迟时间（毫秒）
  pingTimeout: 5000, // 5秒未收到 'pong' 则认为连接断开
  pingInterval: 2000, // 2秒发送一次心跳
  pingMsg: "custom-ping", // 使用自定义的心跳消息
});

const messagelist = ref([]);
const all_message = () => {
  axios.get("http://localhost:3000/message/all_message").then((ele) => {
    if (ele.data.code === 200) {
      messagelist.value = ele.data.data;
    }
  });
};

onMounted(() => {
  useStore.getuser();
  all_message();

  socket.on("message", (newmessage) => {
    useStore.top(newmessage.from);
    all_message();
  });
});

// 删除
const del = (id) => {
  useStore.delete(id);
};

// 置顶
const istop = (id) => {
  useStore.changeistop(id);
};

// 聊天室
const go_chat = (ele) => {
  router.push({
    path: "/chatroom",
    query: { id: ele._id, name: ele.uname, imgsrc: ele.imgsrc },
  });
  useStore.restore(ele._id);
};

// 新消息
const new_message = (ele) => {
  const filtered = messagelist.value.filter(
    (item) =>
      (item.from === useStore.info._id || item.from === ele._id) &&
      (item.to === ele._id || item.to === useStore.info._id)
  );

  if (filtered.length === 0) {
    return "";
  }

  if (filtered.slice(-1)[0].voice) {
    return ["[语音]", filtered.slice(-1)[0].time];
  } else {
    return [filtered.slice(-1)[0].message, filtered.slice(-1)[0].time];
  }
};
</script>
  
<style scoped>
* {
  margin: 0;
  padding: 0;
}

.goods-card {
  margin: 0;
  background-color: "#fff";
}

.button {
  width: 5rem;
  height: 100%;
}

#message {
  width: 100%;
  height: 100%;
}

.search {
  width: 70%;
  margin-left: 15%;
  height: 2rem;
  margin-top: 4%;
  margin-bottom: 4%;
}

.list {
  width: 100%;
}

.ls {
  width: 100%;
  height: 4.9rem;
  position: relative;
  border-bottom: 1px solid rgb(218, 218, 218);
  box-sizing: border-box;
}

.tou {
  width: 4rem;
  height: 4rem;
  border-radius: 50%;
  margin-left: 5%;
  margin-top: 2%;
}

.go {
  width: 2rem;
  height: 1.8rem;
  margin-left: 5%;
  float: right;
  margin-top: 0.7rem;
  margin-right: 2rem;
}

.ls_name {
  position: absolute;
  font-size: 1.2rem;
  margin-left: 5%;
  margin-top: 2%;
  max-width: 6rem;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 超出部分显示为省略号 */
}

.ls_test {
  position: absolute;
  font-size: 1rem;
  margin-left: 5%;
  margin-top: 11%;
  color: #767676;
  max-width: 12rem;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 超出部分显示为省略号 */
}

.ls_time {
  position: absolute;
  color: #767676;
  font-size: 0.9rem;
  margin-left: 44%;
  margin-top: 12%;
}

.red {
  display: inline-block;
  width: 0.7rem;
  height: 0.7rem;
  border-radius: 50%;
  background-color: rgb(255, 0, 0);
  position: absolute;
  margin-left: 70%;
  margin-top: 1.7%;
}
</style>